package com.springboot.springboot4.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @ClassName:
 * @author: CKC
 * @DateTime: 2021/1/22 10:57
 * <p>
 * 自定义数据源
 */


@Deprecated   //这是一个过时的配置注解
//@Configuration
public class MyDataSourceConfig {
//    默认的自动配置是判断容器中没有DataSource才配置数据源	@ConditionalOnMissingBean(DataSource.class)
//    org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration.java
    
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();

//        druidDataSource.setUrl();
//        druidDataSource.setUsername();
//        druidDataSource.setPassword();
        //加入监控功能  stat    SQL注入防火墙功能 wall
        
        
        //这里面能用set方法设置的都可以在yaml配置文件里面配置
//        druidDataSource.setFilters("stat,wall");
        
//        druidDataSource.setMaxActive(10);    设置最大活跃数
        return druidDataSource;
    }
    
    /**
     * 配置druid 的监控页功能
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        
        registrationBean.addInitParameter("loginUsername", "admin");
        registrationBean.addInitParameter("loginPassword", "123456");
        
        
        return registrationBean;
    }
    
    
    /**
     * webStatFilter    用于采集 web-jdbc 关联监控的数据
     * @return
     */
    
    @Bean
    public FilterRegistrationBean webStatFilter(){
    
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(webStatFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return  filterRegistrationBean;
    }
    
}
